package org.lql.algo.codecrush.week009.question.type.II;

import org.lql.algo.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author: liangqinglong
 * @date: 2025-08-20 16:55
 * @description: LCR 151. 彩灯装饰记录 III <a href="https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/description/">...</a>
 **/
public class DecorateRecordIII {

	public List<List<Integer>> decorateRecord(TreeNode root) {
		List<List<Integer>> ans = new ArrayList<>();
		if (root == null) {
			return ans;
		}
		// 双端队列：奇数层从左到右，偶数层从右到左
		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(root);
		while (!queue.isEmpty()) {
			int size = queue.size();
			LinkedList<Integer> level = new LinkedList<>();
			for (int i = 0; i < size; i++) {
				TreeNode node = queue.poll();
				if (ans.size() % 2 == 0) {
					level.addLast(node.val);
				} else {
					level.addFirst(node.val);
				}
				if (node.left != null) {
					queue.offer(node.left);
				}
				if (node.right != null) {
					queue.offer(node.right);
				}
			}
			ans.add(level);
		}
		return ans;
	}

	public static void main(String[] args) {
		DecorateRecordIII decorateRecordIII = new DecorateRecordIII();

		TreeNode root = new TreeNode(8);

		root.left = new TreeNode(17);
		root.right = new TreeNode(21);

		root.right.right = new TreeNode(6);
		root.left.left = new TreeNode(18);

		root.left.left.left = new TreeNode(19);
		root.left.left.right = new TreeNode(20);
		root.right.right.left = new TreeNode(15);

		root.left.left.left.left = new TreeNode(16);
		root.left.left.left.right = new TreeNode(17);
		List<List<Integer>> ans = decorateRecordIII.decorateRecord(root);
		System.out.println(ans);
	}
}
